package cn.acewill.yxd.yunxundian.ui.sign;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.PlanInfoAdapter;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.wentifenxiBean;
import cn.acewill.yxd.yunxundian.model.xingdongjihuaBean;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

/**
 * Created by XXX on 2017/6/2.
 */

public class SendTaskPlanActivity extends BaseActivity implements View.OnClickListener{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private Dialog dialog;
    private ListView taskPlanList;
    //dialog控件
    private TextView stime,endTime;
    private EditText cman,pinglv,hengliang,mubiao,title;
    private List<xingdongjihuaBean> xinDongList;
    private  List<wentifenxiBean> wentiList;
    private PlanInfoAdapter adapter;
    //默认时间
    private int startYear,startMonth,startDay,endYear,endMonth,endDay;
    private int schid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send_task_plan_view);
        intiView();
        CacheActivity.addActivity(this);
    }

    public void intiView(){
        schid=getIntent().getIntExtra("schid",0);
        Toolbar toolbar = (Toolbar) findViewById(R.id.myToolBar);
        toolbar.setTitle("");
        toolbar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView addplan = (TextView) findViewById(R.id.addplan);
        addplan.setOnClickListener(this);
        TextView back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(this);
        this.taskPlanList= (ListView) findViewById(R.id.taskPlanList);
        defultTime();
        loadLocalData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_task_submit,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.submitData:
                sendPlan();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void showMyDialog(){
        dialog=new Dialog(this,R.style.BottomDialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(R.layout.taskplan_detail);
        initDialog();
        dialog.setCanceledOnTouchOutside(false);
        final Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.AnimBottom);
        final WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
        lp.height = this.getWindowManager().getDefaultDisplay().getHeight() * 4/5;
        window.setAttributes(lp);
        dialog.show();
    }

    public void initDialog(){
        this.mubiao= (EditText) dialog.findViewById(R.id.mubiao);
        this.title= (EditText) dialog.findViewById(R.id.title);
        this.stime= (TextView) dialog.findViewById(R.id.stime);
        stime.setOnClickListener(this);
        this.endTime= (TextView) dialog.findViewById(R.id.endTime);
        this.endTime.setOnClickListener(this);
        this.cman= (EditText) dialog.findViewById(R.id.cman);
        this.pinglv= (EditText) dialog.findViewById(R.id.pinglv);
        this.hengliang= (EditText) dialog.findViewById(R.id.hengliang);
        TextView btn_sure= (TextView) dialog.findViewById(R.id.btn_sure);
        btn_sure.setOnClickListener(this);
        TextView btn_cancel= (TextView) dialog.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(this);
    }

    public void defultTime(){
        Calendar calendar=Calendar.getInstance();
        startYear=calendar.get(Calendar.YEAR);
        endYear=calendar.get(Calendar.YEAR);
        startMonth=calendar.get(Calendar.MONTH)+1;
        endMonth=calendar.get(Calendar.MONTH)+1;
        startDay=calendar.get(Calendar.DAY_OF_MONTH);
        endDay=calendar.get(Calendar.DAY_OF_MONTH);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.addplan://添加计划
                showMyDialog();
                break;
            case R.id.back://返回
                finish();
                break;
            case R.id.stime://开始时间
                DatePickerDialog SdatePickerDialog=new DatePickerDialog(this,startListener,startYear,startMonth-1,startDay);
                SdatePickerDialog.show();
                break;
            case R.id.endTime://结束时间
                DatePickerDialog EdatePickDialog=new DatePickerDialog(this,endListener,endYear,endMonth-1,endDay);
                EdatePickDialog.show();
                break;
            case R.id.btn_sure:
                String target=mubiao.getText().toString().trim();
                String thistitle=title.getText().toString().trim();
                String PSTime=stime.getText().toString();
                String PETime=endTime.getText().toString().trim();
                String yardStick=hengliang.getText().toString().trim();
                String principal=cman.getText().toString().trim();
                String frequency=pinglv.getText().toString().trim();
                //判断是否有空值
                if (TextUtils.isEmpty(target)||TextUtils.isEmpty(thistitle)||TextUtils.isEmpty(PSTime)||
                        TextUtils.isEmpty(PETime)||TextUtils.isEmpty(yardStick)||TextUtils.isEmpty(principal)||
                        TextUtils.isEmpty(frequency)){
                    BaseActivity.showAnimaDialog(this,"请将空白处填写完毕");
                    return;
                }else{
                    //数据提交,存储到本地，然后查询出来
                    xingdongjihuaBean bean=new xingdongjihuaBean();
                    bean.setSchid(schid);
                    bean.setMubiao(target);
                    bean.setTitle(thistitle);
                    bean.setStime(startYear+"-"+startMonth+"-"+startDay);
                    bean.setEtime(endYear+"-"+endMonth+"-"+endDay);
                    bean.setCman(principal);
                    bean.setHengliang(yardStick);
                    bean.setPinglv(frequency);
                    try {
                        db.saveOrUpdate(bean);
                        xingdongjihuaBean xingdong=db.selector(xingdongjihuaBean.class)
                                .where("schid","=",schid).findFirst();
                        if (xingdong!=null){
                            dialog.dismiss();
                            loadLocalData();
                        }else{
                            BaseActivity.showAnimaDialog(this,"保存失败");
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.btn_cancel:
                dialog.dismiss();
                break;
        }
    }

    //加载本地数据
    public void loadLocalData() {
        //查询数据
        try {
            xinDongList = db.selector(xingdongjihuaBean.class).where("schid", "=", schid).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        if (xinDongList!=null&&xinDongList.size()>0){
            adapter=new PlanInfoAdapter(this, xinDongList, new PlanInfoAdapter.onPlanDeleteCallBack() {
                @Override
                public void onplandelete(int position) {
                    //弹出框去选择
                    showDeleteDialog(position);
                }
            });
            taskPlanList.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }else{
            BaseActivity.showAnimaDialog(this,"当前无数据，底部进行添加");
        }
    }

    public void showDeleteDialog(final int position){
        MaterialDialogUtils.showMaterialDialog(this, "是否删除当前选中的任务计划", "确定", "取消", true,false,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        xingdongjihuaBean bean=xinDongList.get(position);
                        try {
                            db.delete(bean);
                            xinDongList.remove(position);
                            adapter.notifyDataSetChanged();
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                }, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                });
    }

    //任务计划提交
    public void sendPlan(){
        //拿到问题分析数据
        try {
            wentiList=db.selector(wentifenxiBean.class).where("schid","=",schid).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        } if (wentiList!=null&&wentiList.size()==0){
            MaterialDialogUtils.showMaterialDialog(this, "问题分析不能为空，是否跳转到问题分析进行添加", "确定", "取消", true,false,
                    new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            finish();
                        }
                    }, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        }
                    });
            return;
        }
        if (xinDongList==null){
           showAddDialog();
            return;
        }else if (xinDongList.size()<=0){
            showAddDialog();
            return;
        }
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("正在提交数据");
        dialog.show();
        dialog.setCanceledOnTouchOutside(true);
        Gson gson =new Gson();
        Map<String,String> map=new HashMap<>();
        map.put("task","addShopTodo");
        map.put("xingdongjihua",gson.toJson(xinDongList));
        map.put("wentifenxi",gson.toJson(wentiList));
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] array=result.split("\\|");
                    if (array[0].equals("200")){
                        try {
                            Schedule schedule=db.selector(Schedule.class).where("ID","=",schid).findFirst();
                            if (schedule!=null){
                                schedule.setStates(3);
                                schedule.setIsNeedShopReport(2);
                                db.saveOrUpdate(schedule);
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        //删除db
                        try {
                            for (wentifenxiBean wenti: wentiList){
                                db.deleteById(wentifenxiBean.class,wenti.get_ID());
                            }
                            for (xingdongjihuaBean xindong:xinDongList){
                                db.deleteById(xingdongjihuaBean.class,xindong.get_ID());
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        if (dialog.isShowing()){
                            dialog.dismiss();
                        }
                        BaseActivity.showAnimaDialog(SendTaskPlanActivity.this,"数据提交成功");
                        //要关闭界面
                        CacheActivity.finishActivity();
                        startActivity(new Intent(SendTaskPlanActivity.this,EvaluationMianActivity.class).putExtra("label",1));

                    }else{
                        if (dialog.isShowing()){
                            dialog.dismiss();
                        }
                        if (array.length==4){
                            BaseActivity.showAnimaDialog(SendTaskPlanActivity.this,array[1]);
                        }else{
                            BaseActivity.showAnimaDialog(SendTaskPlanActivity.this,"数据提交失败");
                        }
                    }
                }
                @Override
                public void onFailture() {
                    if (dialog.isShowing()){
                        dialog.dismiss();
                    }
                    BaseActivity.showAnimaDialog(SendTaskPlanActivity.this,"数据提交失败");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    DatePickerDialog.OnDateSetListener startListener=new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            startYear=year;
            startMonth=month+1;
            startDay=dayOfMonth;
            String[] array=changType(startMonth,startDay).split(",");
            stime.setText(startYear+"年"+array[0]+"月"+array[1]+"日");
            compareTime(stime.getText().toString().trim(),endTime.getText().toString().trim());
        }
    };

    DatePickerDialog.OnDateSetListener endListener=new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            endYear=year;
            endMonth=month+1;
            endDay=dayOfMonth;
            String[] array=changType(endMonth,endDay).split(",");
            endTime.setText(endYear+"年"+array[0]+"月"+array[1]+"日");
            compareTime(stime.getText().toString().trim(),endTime.getText().toString().trim());
        }
    };

    //比较时间的大小
    public void compareTime(String startTime,String endTime){
        if (TextUtils.isEmpty(startTime)||TextUtils.isEmpty(endTime)){

        }else{
            String t1= startTime.replace("年","-").replace("月","-").replace("日","-");
            String t2= endTime.replace("年","-").replace("月","-").replace("日","-");
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            try {
                Date date1 = sdf.parse(t1);
                Date date2 = sdf.parse(t2);
                if (date1.after(date2)){
                    BaseActivity.showAnimaDialog(SendTaskPlanActivity.this,"开始日期大于当前时间，请重新选择");
                    stime.setText("");
                    this.endTime.setText("");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private void showAddDialog(){
        MaterialDialogUtils.showMaterialDialog(this, "行动计划不能为空，请点击屏幕下方进行添加", "确定", "取消", true,false,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    }
                }, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                    }
                });
    }

    //修改日期格式
    public String changType(int month,int day){
        String thismonth="";
        String thisday="";
        if (month<10){
            thismonth="0"+month;
        }else{
            thismonth=month+"";
        }
        if (day<10){
            thisday="0"+day;
        }else{
            thisday=day+"";
        }
        return thismonth+","+thisday;
    }

    //返回键监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK) {
            if (dialog != null) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                } else {
                    finish();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
